package com.feign.feignClient.coder;

import com.alibaba.fastjson.JSONObject;
import feign.FeignException;
import feign.Response;
import feign.codec.Decoder;

import java.io.BufferedReader;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Optional;

/**
 * 自定义Decoder,使用阿里的FastJson
 */
public class MyDecoder implements Decoder {



    @Override
    public Object decode(Response response, Type type) throws FeignException, IOException {
        if (response.status() == 200){
            BufferedReader br = new BufferedReader(response.body().asReader() );
            // 存放数据
            StringBuilder builder = new StringBuilder();
            String temp  ;
            while ((temp = br.readLine()) != null) {
                builder.append(temp);
                builder.append("\r\n");
            }
            String  result = builder.toString().trim() ;
            try {
                //加载类
                Class cls = Class.forName(type.getTypeName());
                //实例下塑造型返回
                return JSONObject.parseObject(result,cls.newInstance().getClass() );
            } catch (ClassNotFoundException | IllegalAccessException | InstantiationException e) {
                e.printStackTrace();
            }

        }
        return Optional.empty();

    }


}
